package com.code.zg.news.model.http;

import com.code.zg.news.BuildConfig;
import com.code.zg.news.config.Constants;
import com.code.zg.news.model.bean.WelcomeBean;
import com.code.zg.news.utils.ApkUtils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;

/**
 * Created by zhanggang on 2017/2/22.
 */

public class RetrofitHelper {
    private static OkHttpClient okHttpClient = null;
    private static ZhihuApis zhihuApiService = null;

    private void init(){
        okHttpClient=initOkHttp();
        zhihuApiService = getApiService(ZhihuApis.HOST, ZhihuApis.class);

    }
    public RetrofitHelper(){
        init();
    }
    private OkHttpClient initOkHttp() {
       OkHttpClient.Builder okHttpClientBuilder=new OkHttpClient().newBuilder();
        if(BuildConfig.DEBUG){
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
            okHttpClientBuilder.addInterceptor(loggingInterceptor);
        }
        final Cache cache = new Cache(new File(Constants.PATH_CACHE),1024*1024*50);
        okHttpClientBuilder.cache(cache);
        Interceptor cacheInterceptor=new Interceptor(){

            @Override
            public Response intercept(Chain chain) throws IOException {

                Request request = chain.request();
                if(!ApkUtils.isNetworkConnected()) {
                    request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                }
                Response response = chain.proceed(request);
                int maxAge=0;
                if(ApkUtils.isNetworkConnected()){
                    response.newBuilder()
                            .header("Cache-Control","public, only-if-cached, max-stale="+maxAge)
                            .removeHeader("Pragma")
                            .build();
                }else{
                    int maxStale=60*60*24*28;
                    response.newBuilder()
                            .header("Cache-Control","public, only-if-cached, max-stale="+maxStale)
                            .removeHeader("Pragma")
                            .build();

                }

                return response;
            }
        };
        okHttpClientBuilder.addNetworkInterceptor(cacheInterceptor);
        okHttpClientBuilder.retryOnConnectionFailure(true);
        okHttpClientBuilder.readTimeout(20, TimeUnit.SECONDS);
        okHttpClientBuilder.writeTimeout(20,TimeUnit.SECONDS);
        okHttpClientBuilder.connectTimeout(20,TimeUnit.SECONDS);
        return okHttpClientBuilder.build();
    }
    public <T>T getApiService(String hostUrl,Class<T>clazz) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(hostUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(clazz);
    }
    public Observable<WelcomeBean> fetchWelcomeInfo(String res) {
        return zhihuApiService.getWelcomeInfo(res);
    }
}
